package mbp.logger;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;

import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.soap.SOAPBinding;

import org.apache.log4j.Logger;

import pl.edu.agh.logview.webservice.LogServerReceiver;
import pl.edu.agh.logview.webservice.LogServerReceiverImpl;
import pl.edu.agh.logview.webservice.MessageBean;


public class LoggerThread extends Thread {
	
    private static final String PROTOCOL = "http://";
	private static final String WSDL_PATH = "logServerReceiver?wsdl";
	private static final String SERVICE_CLASS_NAME = "LogServerReceiver";
	private static final String NAMESPACE = "http://webservice.logview.agh.edu.pl/";
	private static final String PORT = "9000";
	private static final String HOST = "localhost";
    
    
	private static final QName SERVICE_NAME = new QName(NAMESPACE, SERVICE_CLASS_NAME);
    private static final QName PORT_NAME    = new QName(PORT, SERVICE_CLASS_NAME+"Port");
	
    // Konfiguracja Endpointów
	private static final String endpointAddress = PROTOCOL + HOST + ":" + PORT + "/" + WSDL_PATH;
	private Service service;
    private LogServerReceiver lsr;
	
	private Logger logger = Logger.getLogger(this.getClass());
    private Boolean serverRunning = true; 
    
	public LoggerThread() {
		this.setPriority(Thread.MIN_PRIORITY);
		try {
			service = Service.create(new URL(endpointAddress),SERVICE_NAME);
		    service.addPort(PORT_NAME, SOAPBinding.SOAP11HTTP_BINDING, endpointAddress);        
		    lsr = service.getPort(LogServerReceiver.class);
		} catch (MalformedURLException e) {
			logger.error(e);
			serverRunning = false;
		} catch (WebServiceException e) {
			logger.error(e);
			serverRunning = false;
		}
	}
	
	public void run(){
		while(serverRunning){
			try {
				//liczymy opóźnienie
				long time1=Calendar.getInstance().getTimeInMillis();
				long time2=lsr.checkTime();
				long time3=Calendar.getInstance().getTimeInMillis();
				long lateEstimate=((time2-time3)+(time2-time1))/2;
				
				System.out.println("Late estimate equals : "+lateEstimate);
				//zmieniamy czas
				MessageBean	toSend=LoggerProxy.takeMessage();
				Date messageTime=toSend.getTime();
				lateEstimate=lateEstimate+messageTime.getTime();
				messageTime.setTime(lateEstimate);
				toSend.setTime(messageTime);
				
				//wysyłamy
				lsr.pushMessage(toSend);
				
			} catch (InterruptedException e) {
				logger.error(e);
			} catch (WebServiceException e) {
				logger.error(e);
				serverRunning = false;
			}
		}
	}
}
